//
//  BlockPrtyMainView.m
//  blockprty
//
//  Created by Alex Shepard on 7/16/11.
//  Copyright 2011 Eye-Fi. All rights reserved.
//

#import "BlockPrtyMainView.h"
#import "ScrollWheelView.h"
#import "blockprtyAppDelegate.h"
#import <MediaPlayer/MediaPlayer.h>

@interface BlockPrtyMainView (private)
- (void) loadTrackForMapLocation;
@end

@implementation BlockPrtyMainView

- (void)authorizeRdio
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	if ([defaults objectForKey:@"RdioAccessToken"]) {
		[rdio authorizeUsingAccessToken:[defaults objectForKey:@"RdioAccessToken"] fromController:self];
	} else {
		[rdio authorizeFromController:self];
	}	
}	

#pragma mark -
#pragma mark Button Interaction

- (IBAction)playButtonWasPressed:(id)sender
{
	// if the app is paused or stopped, begin playback
	if ([rdio.player state] == RDPlayerStatePaused || [rdio.player state] == RDPlayerStateStopped) {		
		[rdio.player play];
	}
}

- (IBAction)pauseButtonWasPressed:(id)sender
{
	// if the app is playing, pause
	if ([rdio.player state] == RDPlayerStatePlaying) {
		[rdio.player togglePause];
	}
}

- (IBAction)authorizeRdioButtonWasPressed:(id)sender
{
	NSLog(@"authorize rdio button was pressed");
	[self authorizeRdio];
	[authorizeRdioButton setTitle:@"Authorizing..." forState:UIControlStateNormal];
	[authorizeRdioButton setEnabled:NO];
}

- (void)rdioDidAuthorizeUser:(NSDictionary *)user withAccessToken:(NSString *)accessToken
{
	// hide the authorize button
	[authorizeRdioButton setHidden:YES];
	
	NSLog(@"rdio authorized user %@ with access token %@", user, accessToken);

	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:accessToken forKey:@"RdioAccessToken"];
	if ([user objectForKey:@"url"]) {
		// we use this for a email/unique key for our server for this rdio user
		[defaults setObject:[user objectForKey:@"url"] forKey:@"RdioUrl"];
	}
	[defaults synchronize];
	
	rdioIsAuthorized = YES;
	
	MKUserLocation *mapLocationReference = [myMapView userLocation];
	CLLocation *location = [mapLocationReference location];
	MKCoordinateSpan span = MKCoordinateSpanMake(5.0, 5.0);
	CLLocationCoordinate2D coords = [location coordinate];
	MKCoordinateRegion region = MKCoordinateRegionMake(coords, span);
	
	[myMapView setRegion:region];
	
	[self loadTrackForMapLocation];
	
	// send user location info to server
	[self uploadTasteToServer];
}

- (void)uploadTasteToServer
{
	MPMediaQuery *artists = [MPMediaQuery artistsQuery];
	
	NSMutableSet *allArtists = [[NSMutableSet alloc] init];
	
	NSArray *itemsFromGenericQuery = [artists items];
	for (MPMediaItem *song in itemsFromGenericQuery) {
		NSString *artistName = [song valueForProperty: MPMediaItemPropertyArtist];
		[allArtists addObject:artistName];
	}
	
	NSMutableString *artistList = [[NSMutableString alloc] init];
	int index = 0;
	for (NSString *artistName in allArtists) {
		if (index > 10) {
			break;
		}
		if (index != 0) {
			[artistList appendString:@"|"];
		}
		[artistList appendString:artistName];
		index++;
	}
	NSLog(@"artist list is %@", artistList);
	
	blockprtyAppDelegate *appDelegate = (blockprtyAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	MKUserLocation *mapLocationReference = [myMapView userLocation];
	CLLocation *location = [mapLocationReference location];
	CLLocationCoordinate2D coords = [location coordinate];
	
	NSString *user = nil;
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	if ([defaults objectForKey:@"url"]) {
		user = [defaults objectForKey:@"url"];
	} else {
		user = @"blah di blah blah random user";
	}
	
	[appDelegate submitTasteForLatitude:coords.latitude 
							  longitude:coords.longitude
						   artistString:artistList
								   user:user];	
}

- (void)playTrack:(id)result
{
	NSString *resultString = (NSString *)result;
	NSArray *resultArray = [resultString componentsSeparatedByString:@"|"];
	if ([resultArray count] < 3) {
		NSLog(@"skipping garbage 'track' from server: %@", result);
		// do nothing
		return;
	}
	
	NSLog(@"asked to play track %@", result);
	if ([[resultArray objectAtIndex:0] isEqualToString:trackKey]) {
		return;
	}
	
	trackKey = [resultArray objectAtIndex:0];
	trackTitle = [resultArray objectAtIndex:1];
	artist = [resultArray objectAtIndex:2];

	[rdio.player playSource:trackKey];
	
	NSString *trackInfo = [NSString stringWithFormat:@"%@ - %@", artist, trackTitle];
	[trackInfoLabel setText:trackInfo];
}
	

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
	[self loadTrackForMapLocation];
}

- (void) loadTrackForMapLocation
{
	blockprtyAppDelegate *appDelegate = (blockprtyAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	CLLocationCoordinate2D mapCenter = [myMapView centerCoordinate];
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSString *user = nil;
	if ([defaults objectForKey:@"url"]) {
		user = [defaults objectForKey:@"url"];
	} else {
		user = @"blah di blah blah random user";
	}
	
	[appDelegate loadTrackToPlayForLatitude:mapCenter.latitude 
								  longitude:mapCenter.longitude
									  range:1
								  authToken:[defaults objectForKey:@"RdioAccessToken"]
									   user:user];
}


- (void)rdioAuthorizationFailed:(NSString *)error
{
	NSString *retryMsg = [NSString stringWithFormat:@"%@\n\nRetry?", error];
	[authorizeRdioButton setTitle:retryMsg forState:UIControlStateNormal];

	[authorizeRdioButton setEnabled:YES];
}

- (void)rdioAuthorizationCancelled
{
	[authorizeRdioButton setTitle:@"Authorize Rdio" forState:UIControlStateNormal];
	[authorizeRdioButton setEnabled:YES];
}

-(void)rdioDidLogout
{
	NSLog(@"rdio logged out");
}


// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
		rdio = [[Rdio alloc] initWithConsumerKey:@"adj7yp32zsua2nvtkdrhef6w" andSecret:@"BWpE88arYY" delegate:self];
    }
	
    return self;
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];	
}

- (void)viewDidAppear:(BOOL)animated
{
	[super viewDidAppear:animated];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

@end
